package cn.itsource.ymjs.service.impl;

import cn.itsource.ymjs.dto.CourseVideoDTO;
import cn.itsource.ymjs.entity.CourseVideo;
import cn.itsource.ymjs.entity.FitnessCourse;
import cn.itsource.ymjs.exception.GlobalException;
import cn.itsource.ymjs.query.CourseQuery;
import cn.itsource.ymjs.repository.CourseVideoRepository;
import cn.itsource.ymjs.repository.FitnessCourseRepository;
import cn.itsource.ymjs.result.PageResult;
import cn.itsource.ymjs.service.ICourseVideoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * @author SuperJellyfish
 * @description TODO
 * @date 2022/2/3 16:30
 */
@Transactional(rollbackFor = Exception.class)
@Service
public class CourseVideoServiceImpl extends BaseServiceImpl<CourseVideo, CourseQuery> implements ICourseVideoService {

    @Autowired
    private FitnessCourseRepository fitnessCourseRepository;

    @Autowired
    private CourseVideoRepository repository;
    @Override
    public List<CourseVideoDTO> getAll() {
        List<CourseVideo> courseVideos = super.selectAll();
        CourseVideoDTO courseVideoDTO = new CourseVideoDTO();
        List<CourseVideoDTO> courseVideoDTOs = new ArrayList<>(16);
        courseVideos.forEach((courseVideo) -> {
            FitnessCourse one = fitnessCourseRepository.getOne(courseVideo.getCourseId());
            courseVideoDTO.setCourseName(one.getName());
            BeanUtils.copyProperties(courseVideo, courseVideoDTO);
            courseVideoDTOs.add(courseVideoDTO);
        });
        return courseVideoDTOs;
    }

    @Override
    public PageResult selectPage(CourseQuery courseQuery) {
        /**=====================================zs处理排序=====================================**/
        Pageable pageable = creatPageable(courseQuery);;
        /**=====================================带条件查询=====================================**/
        Specification specification = createWhereForSelectPage(courseQuery);
        /**=====================================执行查询=====================================**/
        Page<CourseVideo> courseVideos = null;
        Page<CourseVideoDTO> courseVideoDTOS = null;
        if(specification == null){
             courseVideos = repository.findAll(pageable);

        }else{
            if(!(repository instanceof JpaSpecificationExecutor)){
                throw new GlobalException("repository 不是 JpaSpecificationExecutor的子类");
            }

            JpaSpecificationExecutor repository = (JpaSpecificationExecutor) this.repository;
            courseVideos = repository.findAll(specification,pageable);

            List<CourseVideoDTO> courseVideoDTOs = new ArrayList<>(16);
            courseVideos.getContent().forEach((courseVideo) -> {
                CourseVideoDTO courseVideoDTO = new CourseVideoDTO();
                BeanUtils.copyProperties(courseVideo, courseVideoDTO);
                FitnessCourse one = fitnessCourseRepository.getOne(courseVideo.getCourseId());
                courseVideoDTO.setCourseName(one.getName())
                        .setCourseTypeName(one.getCourseType().getName());

                courseVideoDTOs.add(courseVideoDTO);
            });
            courseVideoDTOS = new PageImpl<>(courseVideoDTOs);
        }
        /**=====================================封装结果=====================================**/

        return new PageResult(courseVideos.getTotalElements(),courseVideoDTOS.getContent());
    }
    @Override
    protected Specification createWhereForSelectPage(CourseQuery courseQuery) {
        return (Specification<FitnessCourse>) (root, query, criteriaBuilder) -> {
            if(courseQuery.getKeyword() != null){
                //关键字模糊查询
                Predicate p1 = criteriaBuilder.like(root.get("name").as(String.class), "%"+courseQuery.getKeyword()+"%");
                query.where(criteriaBuilder.and(p1));
            }
            return query.getRestriction();
        };
    }
}
